#usr/bin/python

import re


#ENTRY       C18204                      Compound
#NAME        2,2',4,5'-Tetrabromodiphenyl ether;
#            PBDE 49;
#            BDE 49
#FORMULA     C12H6Br4O
#MASS        481.7152



class kegg_parser:

	# only looking for for wanted formula, to much RAM if we take all
	
	def __init__(self, kegg_file):
		self.data = kegg_file

	def parsing (self):
		lst =[]
		entry = re.compile ('ENTRY\s+(C\d+).+\n')
		mass = re.compile('MASS\s+(\d+\.\d+)\n')
		corrupted = False
		with open(self.data) as f:
			line =f.readline()
			#continue until EOF
			while line != "" :
				corrupted =False
				if entry.match(line):
					dico ={}
					dico["ENTRY"] = entry.match(line).group(1)
					lines =[];
					while mass.match(line) is None and not corrupted:
						line =f.readline()
						#corrupted don't find mass before a new ENTRY
						if line.split(" ")[0] == "ENTRY":
							corrupted =True
						lines.append(line)
					#exclude corruption
					if not corrupted:
							#line
						dico["MASS"] = mass.match(line).group(1)
						for l in lines:
							if l.split(" ")[0] == "NAME":
								dico["NAME"] = l.split(" ")[8]
								#try to get all the name
								if len(l) > 8:
									for i in xrange (8, len(l)):
										dico["NAME"] += l[i]
								
							elif l.split(" ")[0] == "FORMULA":
								dico["FORMULA"] = l.split(" ")[5].split("\n")[0]
						lst.append(dico)
								#if l.split(" ")[5].split("\n")[0] == formula:
								#	return dico
							#condition to break
					else:
						del dico
				line =f.readline()
			return lst
				
	
	def fast_parsing (self, formula):
		form = re.compile ('FORMULA\s+(.+)\n')
		with open(self.data) as f:
			line =f.readline()
			while line is not False:
				if form.match(line):
					if form.match(line).group(1) == formula:
						return True
				line =f.readline()
			return False
			
if __name__ =="__main__":
	import sys
	p = kegg_parser("..\KEGG.txt") #C:\Users\Marco\Desktop\msapipe
	c =p.parsing()#C19H17NO4
	if c:
		for dic in c:
			print dic["FORMULA"]
		print "finished"

	#print p.fast_parsing("C19H17NO4")
	#sys.exit(0)
	
	
		